package com.bookbuf.library;

import android.database.DataSetObservable;
import android.database.DataSetObserver;

/**
 * （应对首次数据加载时）当数据源发生变更时，对应布局也相应变更。
 */
public abstract class LoadingLayoutAdapter<Data> implements IBindableAdapter<Data>, IStateManager {


	/*请求数据*/
	protected Data data = null;
	/*加载状态*/
	protected State state = State.INIT;

	@Override
	public void bind (Data data) {
		this.data = data;
		if (isEmpty ()) {
			setState (State.SUCCESS_EMPTY);
		} else {
			setState (State.SUCCESS_NOT_EMPTY);
		}
	}

	@Override
	public void unbind () {
		setState (State.INIT);
		this.data = null;
	}

	/*观察者*/
	private final DataSetObservable mDataSetObservable = new DataSetObservable ();

	public void registerDataSetObserver (DataSetObserver observer) {
		mDataSetObservable.registerObserver (observer);
	}

	public void unregisterDataSetObserver (DataSetObserver observer) {
		mDataSetObservable.unregisterObserver (observer);
	}

	/**
	 * 通知观察者们数据已经变更，需要更新视图。
	 */
	public void notifyDataSetChanged () {
		mDataSetObservable.notifyChanged ();
	}

	/**
	 * 通知观察者们数据已经失效，从而不需要继续监听数据的变更。
	 */
	public void notifyDataSetInvalidated () {
		mDataSetObservable.notifyInvalidated ();
	}

	protected enum State {

		/** 初始化 */INIT,
		/** 加载中 */LOADING,
		/** 加载成功并且数据非空 */SUCCESS_NOT_EMPTY,
		/** 加载成功并且数据为空 */SUCCESS_EMPTY,
		/** 加载错误 */ERROR;
	}

	private void setState (State state) {
		this.state = state;
		notifyDataSetChanged ();
	}

	public State getState () {
		return state;
	}

	@Override
	public void bindError () {
		setState (State.ERROR);
	}

	@Override
	public void bindLoading () {
		setState (State.LOADING);
	}

}
